#pragma once

#include "sanimation.h"
#include "button.h"
#include "sprite.h"

class SAnimationEntry : public Button
{
protected:
	Sprite * m_sprite;
	int m_animationIndex;
	int m_frameIndex;
public:
	virtual bool handleEvent(const SDL_Event & e)
	{
		switch(e.type)
		{
			// figure out which frame was clicked on...
		case SDL_MOUSEBUTTONDOWN:
			switch(e.button.button)
			{
			case SDL_BUTTON_LEFT:{
				SRect area = *getAnimation()->getFrameSize();
				area.setPosition(getArea()->getMin());
				SPoint click = SPoint(e.button.x, e.button.y);
				click.subtract(getArea()->getMin());
				SPoint dim = area.getDimension();
				if(dim.x && dim.y)
				{
					click.divide(dim);
					if(click.y == 0 && click.x < getAnimation()->getFrameCount())
					{
						m_frameIndex = click.x;
					}
				}
				else
				{
					m_frameIndex = 0;
				}
			}break;
			}
			break;
		}
		return Button::handleEvent(e);
	}
	inline int getAnimationIndex(){return m_animationIndex;}
	inline int getFrameIndex(){return m_frameIndex;}
	SAnimation * getAnimation()
	{
		return m_sprite->getAnimation(m_animationIndex);
	}
	void refreshArea()
	{
		getAnimation()->invalidateFrameSize();
		SRect area = *getAnimation()->getFrameSize();
		SRect completeArea(area);
		completeArea.add(area.unitsOver(SPoint(getAnimation()->getFrameCount()-1, 0)));
		completeArea.setPosition(SPoint(0,0));
		if(!completeArea.isValid())
		{
			completeArea.setDimension(SPoint(25,25));
		}
		if(m_parent->getArea()->getWidth() > completeArea.getWidth())
		{
			completeArea.setWidth(m_parent->getArea()->getWidth());
		}
		setArea(completeArea);
		setDirty(0);
	}
	void draw(SDL_Surface * a_surface)
	{
		SAnimation * sa = getAnimation();
		SFrame * sf;
		SRect area = *sa->getFrameSize();
		if(!area.isValid())
		{
			area.setDimension(SPoint(25,25));
		}
		SRect areaCursor(area);
		SPoint cursor(getArea()->getMin());
		areaCursor.setPosition(cursor);
		for(int f = 0; f < sa->getFrameCount(); ++f)
		{
			sf = sa->getFrame(f);
			sf->draw(a_surface, cursor.difference(SPoint(area.getX(), area.getY())), 0, 1);
			cursor.addX(area.getWidth());
			if(m_animationIndex != m_sprite->getAnimationIndex() || f != m_sprite->getFrameIndex())
				VSDL_drawRect(a_surface, &areaCursor, 0, 1);
			else
				VSDL_drawRect(a_surface, &areaCursor, -1, 2);
			areaCursor.setX(cursor.getX());
		}
	}
	SAnimationEntry():m_sprite(0),m_animationIndex(-1),m_frameIndex(0){}
	SAnimationEntry(Sprite * a_sprite, const int & a_animationIndex)
	{
		m_sprite = a_sprite;
		m_animationIndex = a_animationIndex;
	}
};